<template>
  <div class="sidebar">
    <el-scrollbar view-style="height:100%;" view-class="flex-column">
      <div class="sidebar-header">
        <img
          class="logo"
          src="@/assets/images/home/icons/logo.png"
          @click="router.push({ name: 'index' })"
        />
      </div>
      <el-menu class="menu-container" :default-active="activePath" router>
        <SubjectSelect />
        <el-menu-item
          v-for="item in menuData"
          :key="item.path"
          :index="item.index"
          :route="{ path: item.fullPath }"
          :disabled="item.disabled"
          @click="handleMenuClick(item)"
          @mouseenter="handleMouseEnter(item.path)"
          @mouseleave="handleMouseLeave"
          class="menu-item"
          :class="{
            active:
              route.fullPath.includes(item.path) ||
              hoveredPath === item.path ||
              route.fullPath.includes(item.activePath)
          }"
        >
          <template #title>
            <div class="menu-item-title">
              <i :class="['icon', item.icon]"></i>
              <span class="text"> {{ item.title }}</span>
            </div>
          </template>
        </el-menu-item>
      </el-menu>
      <!-- <div
        class="message-center"
        :class="{ active: route.path.includes('messageCenter') }"
        @click="router.push({ name: 'messageCenter' })"
      >
        <img :src="messageIcon" class="icon-bell" />
      </div> -->
      <div class="user-block">
        <el-popover
          placement="right"
          width="0.7rem"
          trigger="hover"
          popper-style="padding: 0; min-width: 0;"
          :offset="30"
          @before-enter="beforeEnterPopover"
          @before-leave="isShowRoles = false"
        >
          <template #reference>
            <div class="trigger">
              <img
                src="@/assets/images/common/icon-setting.png"
                class="setting-img"
              />
              <span>信息管理</span>
              <span class="i-arrow-right" v-html="ArrowRight"> </span>
            </div>
          </template>
          <ul class="tab-list">
            <li class="role" v-if="!onlyTeacher">
              <!-- 这个判断逻辑没有涉及完善，需等待后端接口完善 -->
              <div class="active-role" @click="isShowRoles = !isShowRoles">
                <span class="now-role">{{ nowGlobalRole?.role_name }}</span>
                <span class="arrow-right" v-html="ArrowRight"></span>
                <div class="roles">
                  <!-- <img src="@/assets/images/common/i-left-arrow.svg?url"> -->
                  <div class="inner-list">
                    <div
                      class="role-item teacher"
                      v-if="onlyTeacher || userInfo.subjectList?.length"
                      :class="{
                        active: nowGlobalRole?.role_code === ''
                      }"
                      @click="
                        changeRole({ role_name: '任课老师', role_code: '' })
                      "
                    >
                      <span>任课老师</span>
                    </div>
                    <div
                      v-for="role in filteredRoles"
                      :key="role?.role_code"
                      class="role-item"
                      :class="{
                        active: role?.role_code === nowGlobalRole?.role_code
                      }"
                      @click.stop="changeRole(role)"
                    >
                      {{ role?.role_name }}
                    </div>
                  </div>
                </div>
              </div>
            </li>
            <li
              class="tab-item"
              @click="
                router.push({
                  name: 'classManage'
                })
              "
            >
              我的班级
            </li>
            <li class="tab-item" @click="jumpSchoolManage">
              <span>{{
                userInfo.organ_type === '104' ? '学校管理' : '门店管理'
              }}</span>
              <i class="lock-icon" v-if="!filteredRoles.length"></i>
            </li>
            <li class="tab-item" @click="router.push({ name: 'userInfo' })">
              个人资料
            </li>
            <!-- <li class="tab-item" @click="onLayerSet">分层配置</li> -->
            <li
              class="tab-item logout"
              :class="{ clicked: isClick }"
              @click="logout"
              @mousedown="changeStyle(true)"
              @mouseup="changeStyle(false)"
              @mouseleave="changeStyle(false)"
            >
              退出登录
            </li>
          </ul>
        </el-popover>
      </div>
    </el-scrollbar>
    <el-dialog v-model="isShowTips" width="500" :show-close="false">
      <div class="tips-header">
        <div class="title">
          {{ userInfo.organ_type === '104' ? '学校管理' : '门店管理' }}
        </div>
        <div class="close" @click="isShowTips = false"></div>
      </div>
      <div class="tips-content">
        <div class="text">
          <i class="info-icon"></i>
          <span class="tips-text">
            抱歉，您不是{{ adminText }}，无权限设置，请咨询{{ adminText }}。
          </span>
        </div>
        <div class="admin-list">
          <div
            class="admin-item"
            v-for="item in adminList"
            :key="item.person_id"
          >
            <div class="name-icon">{{ item.person_name.slice(0, 1) }}</div>
            <div class="admin-name">
              <div class="name-title">{{ adminText }}</div>
              <div class="name-text">{{ item.person_name }}</div>
            </div>
            <div class="admin-phone">
              <div class="phone-title">联系电话</div>
              <div class="phone-text">{{ item.phone }}</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowTips = false">取消</el-button>
          <el-button type="primary" @click="isShowTips = false">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <LayerDrawer v-if="layerVis" v-model:visible="layerVis" />
</template>
<script setup>
import { onBeforeMount, ref, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

import { storeToRefs } from 'pinia'
import { useAuthStore, useKnowledgeStore } from '@/stores'
import { schoolManage, storeManage } from '@/apis/host'
import { getRoleByTeacherId, postLogout, getAdminList } from '@/apis'
import { getBasketQuestion } from '@/apis/assignment/index'
import router from '@/router'

import ArrowRight from '@/assets/images/common/arrow-right.svg?raw'
import MessageActive from '@/assets/images/message/icon-bell-active.svg?url'
import MessageInActive from '@/assets/images/message/icon-bell-inactive.svg?url'
import SubjectSelect from './SubjectSelect.vue'
import LayerDrawer from '@/components/publish-task/LayerDrawer.vue'

import { iframeTaskMitt } from '@/utils/tools/bus'

const route = useRoute()
const { reset } = useKnowledgeStore()
const activePath = ref(route.path) // 初始化为当前路径
const hoveredPath = ref('')

const microApps = ['course-center', 'resource-center']

const handleMenuClick = item => {
  if (!microApps.includes(item.path)) {
    return
  }
  iframeTaskMitt.emit('reset-path', {
    item
  })
}

const handleMouseEnter = path => {
  hoveredPath.value = path
}

const handleMouseLeave = () => {
  hoveredPath.value = ''
}

// const getIconURL = iconName => {
//   return new URL(`/src/assets/images/home/icons/${iconName}`, import.meta.url)
//     .href
// }

const messageIcon = computed(() =>
  route.path.includes('messageCenter') ? MessageActive : MessageInActive
)

const layerVis = ref(false)
const onLayerSet = () => {
  layerVis.value = true
}

const menuData = [
  {
    title: '工作台',
    path: 'workbench',
    fullPath: '/index/workbench',
    index: '/index/workbench',
    icon: 'i-workbench',
    children: []
  },
  {
    title: 'AI课程',
    path: 'course-center',
    fullPath: '/question-bank/ai-lesson/list',
    index: '/question-bank/ai-lesson/list',
    icon: 'i-course',
    activePath: '/question-bank/ai-lesson',
    children: []
  },
  {
    title: '任务中心',
    path: 'assignment',
    fullPath: '/index/assignment',
    index: '/index/assignment',
    icon: 'i-task',
    children: []
  },
  {
    title: '资源中心',
    path: 'resource-center',
    fullPath: '/question-bank/resource-center/topics',
    index: '/question-bank/resource-center/topics',
    activePath: '/question-bank/resource-center',
    icon: 'i-question',
    children: []
  },
  {
    title: '靶向提升',
    path: 'target-boost',
    fullPath: '/index/target-boost',
    index: '/index/target-boost',
    icon: 'i-target',
    children: []
  },
  // 去掉学情分析
  // {
  //   title: '学情分析',
  //   path: 'situation-report',
  //   fullPath: '/situation-report',
  //   index: 'situation-report',
  //   icon: 'i-analysis',
  //   children: []
  // },
  {
    title: '教学管理',
    path: 'manage-teaching',
    fullPath: '/index/manage-teaching',
    index: '/index/manage-teaching',
    icon: 'i-manage',
    disabled: true,
    children: []
  }
]

watch(
  () => route.fullPath,
  newPath => {
    const matchedMenuItem = menuData.find(item => newPath.includes(item.path))
    if (matchedMenuItem) {
      activePath.value = matchedMenuItem.fullPath
      console.log(activePath.value)
    }
  },
  {
    immediate: true
  }
)

/* 用户设置 begin */
const authStore = useAuthStore()

// 权限管理
const { filteredRoles, nowGlobalRole, onlyTeacher, userInfo } =
  storeToRefs(authStore)

const isShowRoles = ref(false)
const changeRole = async role => {
  if (role.role_code === nowGlobalRole.value?.role_code) {
    return
  }
  authStore.setNowGlobalRole(role)
  await authStore.getTeachingInfo(role.role_code)
  ElMessage.success(`切换${role.role_name}角色成功`)
  isShowRoles.value = false
}
const getPermission = async () => {
  const res = await getRoleByTeacherId({
    teacherId: authStore.userInfo.userId,
    schoolId: authStore.userInfo.school_id
  })
  if (res.data) {
    authStore.setRoles(res.data)
  }
}

const beforeEnterPopover = async () => {
  await getPermission()
}
onBeforeMount(async () => {
  // 拿缓存中的角色
  if (authStore.nowGlobalRole?.role_code !== '') {
    return
  }
  authStore.setNowGlobalRole({ role_name: '任课老师', role_code: '' })
})

const isShowTips = ref(false)
const adminList = ref([])
const adminText = computed(() => {
  return userInfo.value.organ_type === '104' ? '学校管理员' : '门店管理员'
})
watch(isShowTips, async val => {
  if (!val) {
    return
  }
  const res = await getAdminList({
    schoolId: authStore.userInfo.school_id,
    roleCode: userInfo.value.organ_type === '104' ? 'role|1007' : 'role|1012'
  })
  if (res.data) {
    adminList.value = res.data?.list
  }
})

const jumpSchoolManage = async () => {
  // 有其他角色 才开放学校管理
  if (!filteredRoles.value.length) {
    isShowTips.value = true
    return
  }
  await authStore.getUserInfoFun()
  const {
    school_id,
    school_name,
    sessionId,
    platform,
    userId,
    userType,
    organ_type
  } = authStore.userInfo
  const query = `/?school_id=${school_id}&school_name=${school_name}&token=${sessionId}&platform=${platform}&user_id=${userId}&user_type=${userType}&role_code=${authStore.nowGlobalRole.role_code}`
  // 先随便发个请求验证token是否仍然有效，如果token过期不进行跳转
  const isTokenValid = await getBasketQuestion({
    user_id: userId,
    stage: authStore.nowGlobalStageId,
    subject_id: authStore.nowGlobalSubjectId
  })
  if (!isTokenValid) return
  if (organ_type === '104') {
    window.open(`${schoolManage}${query}`)
  } else {
    window.open(`${storeManage}${query}`)
  }
}
const logout = async () => {
  const { sessionId, userId, userType, platform } = authStore.userInfo
  const params = {
    ACCESSTOKEN: sessionId,
    userId,
    userType,
    platform
  }
  const res = await postLogout(params)
  if (res.F_responseNo === 10000) {
    ElMessage.success('退出成功')
    reset()
    authStore.resetAllStates()
    router.push('/login')
  } else {
    ElMessage.error(res.F_responseMsg)
  }
}
// 给退出登录添加样式
const isClick = ref(false)
const changeStyle = isDown => {
  isClick.value = isDown
}
/* 用户设置 end */
</script>

<style lang="less" scoped>
.sidebar {
  width: 100%;
  height: 100%;
  background-color: #fff;

  :deep(.is-active) {
    background-color: #e9eeff;
    color: #5367dd;
  }

  .sidebar-header {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    height: 96px;
    width: 100%;
    cursor: pointer;

    .logo {
      width: 75%;
      height: 75%;
      object-fit: contain;
    }

    .title {
      font-size: 24px;
      font-weight: bold;
    }
  }
  .tips-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    .title {
      color: rgba(4, 11, 26, 0.8);
      font-family: 'Source Han Sans CN';
      font-size: 18px;
      font-weight: 700;
    }
    .close {
      width: 18px;
      height: 18px;
      cursor: pointer;
      background-image: url(@/assets/images/common/close.png);
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }
  }
  .tips-content {
    display: flex;
    flex-direction: column;
    gap: 10px;
    .text {
      display: flex;
      align-items: center;
      height: 54px;
      padding: 0 24px;
      border-radius: 6px;
      background-color: #fff3d1;
      .info-icon {
        width: 16px;
        height: 16px;
        margin-right: 5px;
        background-image: url(@/assets/images/home/icons/warn-info.svg);
        background-size: 100% 100%;
        background-repeat: no-repeat;
      }
    }

    .admin-list {
      display: flex;
      flex-direction: column;
      gap: 10px;
      :deep(.el-skeleton) {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
      .admin-item,
      .skeleton {
        box-sizing: border-box;
        display: flex;
        justify-content: space-around;
        align-items: center;
        border: 1px dashed #ccc;
        padding: 24px 16px;
        border-radius: 5px;
        .admin-info {
          padding: 0 16px;
          flex: 1;
        }
        .name-icon {
          width: 48px;
          height: 48px;
          line-height: 48px;
          text-align: center;
          line-height: 48px;
          color: #fbc25e;
          background-color: #fff5db;
          border-radius: 50%;
        }
        .name-title {
          font-size: 14px;
          color: #ccc;
        }
        .phone-title {
          font-size: 14px;
          color: #ccc;
        }
      }
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
  }
  :deep(.el-dialog) {
    border-radius: 10px;
    box-shadow: 0px 0px 9.8px 0px rgba(0, 0, 0, 0.15);
  }
}

.menu-container {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  width: 100%;
  border-right: 0;

  .menu-item {
    width: 174px;
    height: 58px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .menu-item-title {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      width: 21px;
      height: 21px;
      margin-right: 16px;
      background-size: cover;
    }

    .text {
      min-width: 74px;
      line-height: 24px;
      font-size: 16px;
      color: #333;
    }
  }

  .i-workbench {
    background-image: url(@/assets/images/common/i-workbench.svg);
  }

  .i-course {
    background-image: url(@/assets/images/common/i-course.svg);
  }

  .i-task {
    background-image: url(@/assets/images/common/i-task.svg);
  }

  .i-paper {
    background-image: url(@/assets/images/common/i-paper.svg);
  }

  .i-question {
    background-image: url(@/assets/images/common/i-question.svg);
  }

  .i-target {
    background-image: url(@/assets/images/common/i-target.svg);
  }

  .i-analysis {
    background-image: url(@/assets/images/common/i-analysis.svg);
  }

  .i-manage {
    background-image: url(@/assets/images/common/i-manage.svg);
  }

  :not(.is-disabled).active {
    background-color: @color-brand-regular;

    .text {
      color: #fff;
    }

    .i-workbench {
      background-image: url(@/assets/images/common/i-workbench-active.svg);
    }

    .i-course {
      background-image: url(@/assets/images/common/i-course-active.svg);
    }

    .i-task {
      background-image: url(@/assets/images/common/i-task-active.svg);
    }

    .i-paper {
      background-image: url(@/assets/images/common/i-paper-active.svg);
    }

    .i-question {
      background-image: url(@/assets/images/common/i-question-active.svg);
    }

    .i-target {
      background-image: url(@/assets/images/common/i-target-active.svg);
    }

    .i-analysis {
      background-image: url(@/assets/images/common/i-analysis-active.svg);
    }

    .i-manage {
      background-image: url(@/assets/images/common/i-manage-active.svg);
    }
  }
}

.message-center {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 25px;
  cursor: pointer;
}

.user-block {
  margin: 0 auto 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;

  .trigger {
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: @radius-component;
    padding: 0 20px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: @size-big;
    cursor: pointer;
    .setting-img {
      width: 24px;
      margin-right: 4px;
    }
  }

  .avatar-img {
    margin-right: 6px;
    width: 20px;
    height: 20px;
  }

  .i-arrow-right {
    display: flex;
    align-items: center;
    margin-left: 12px;
    width: 10px;
    height: 10px;
    color: #696969;
  }
}

.tab-list {
  position: relative;
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
  font-size: 15px;
  color: rgba(4, 11, 26, 0.7);
  padding: 10px 0;

  .role {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;

    &:hover {
      .roles {
        display: flex;
      }
    }

    & > :only-child {
      grid-column: 1 / -1;
    }

    .teacher {
      grid-column: 1 / span 2;
      grid-row: 1 / span 2;
    }
    .active-role,
    .role-item {
      box-sizing: border-box;
      height: 50px;
      line-height: 50px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
    }
    .active-role {
      display: none;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #428fff;
      margin: 0 14px;
      border-bottom: 0.3px solid rgba(4, 11, 26, 0.15);

      .now-role {
        font-weight: 700;
      }

      .arrow-right {
        display: flex;
        align-items: center;
        margin-left: 12px;
        width: 10px;
        height: 10px;
        color: #428fff;
      }
    }
    .role-item {
      &:hover {
        color: #428fff;
        border: none;
      }
    }
    .roles {
      box-sizing: border-box;
      position: absolute;
      display: none;
      flex-direction: column;
      max-height: 100%;
      overflow: hidden;
      gap: 6px;
      top: 0;
      left: 100%;
      background-color: #fff;
      width: 0.7rem;
      padding: 14px;
      border-radius: 5px;
      box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      img {
        position: relative;
        align-items: flex-start;
        z-index: 1;
        width: 16px;
        top: 70px;
        left: -60px;
      }

      .inner-list {
        height: 100%;
        overflow: auto;

        &::-webkit-scrollbar {
          display: none;
        }

        .role-item {
          color: rgba(4, 11, 26, 0.7);
          border: unset;
          &:not(:last-child) {
            border-bottom: 0.3px solid rgba(4, 11, 26, 0.15);
          }

          &:hover {
            color: @color-brand-regular;
            font-weight: 700;
          }
        }
        .active {
          color: @color-brand-regular;
          font-weight: 700;
          // background-color: @color-brand-regular;
        }
      }
    }

    .active {
      color: #428fff;
      font-weight: 700;
      border: none;
    }
  }

  .tab-item {
    text-align: center;
    cursor: pointer;
    height: 50px;
    line-height: 50px;
    transition: all 0.3s;
    margin: 0 14px;

    &:not(:last-child) {
      border-bottom: 0.3px solid rgba(4, 11, 26, 0.15);
    }

    &:hover {
      color: var(--el-color-primary);
      font-weight: 700;
    }
    .lock-icon {
      display: inline-block;
      width: 14px;
      height: 14px;
      vertical-align: text-bottom;
      margin-left: 4px;
      background-image: url(@/assets/images/home/icons/lock.svg);
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }
  }

  .logout {
    box-sizing: border-box;
    color: @color-function-danger-dark;

    &:hover {
      background: unset;
      color: #ff0d00;
    }
  }
  .clicked {
    color: #fff !important;
    background-color: #ff6d65 !important;
  }
}
</style>
